//
//  VideoPrizeClawViewController.m
//  MyApp
//
//  Created by Don on 2017/8/22.
//
//

#import "VideoPrizeClawViewController.h"
#import "UIImage+Color2Image.h"
#import "UIImage+CacheViaName.h"
#import "UIColor+HexColor.h"
//#import "UINavigationController+FDFullscreenPopGesture.h"

#import "PrizeClawVideoHandler.hpp"

#import "MMGPrizeClawOpenGLView.h"
#import "MMGJoyStickView.h"

//#import "MMGSocketClient.h"
#import "MMGVideoPrizeClawView.h"
#import "MMGVideoPrizeClawViewModel.h"

void pcvFrameAvailableCallback(void *ref,uint8_t *frame) {
    
//    printf("VideoPrizeClawViewController :%p",ref);
    VideoPrizeClawViewController *vpcVC = (__bridge VideoPrizeClawViewController *)ref;
    [vpcVC renderFrame:frame];
//    DLog(@"VideoPrizeClawViewController:%@ frame available ",ref);
}
void pcvFrameErrorCallback(void *ref , const int error) {
    printf("VideoPrizeClawViewController:%p error :%d ",ref,error);
    VideoPrizeClawViewController *vpcVC = (__bridge VideoPrizeClawViewController *)ref;
    [vpcVC frameError:""];
    
}

@interface VideoPrizeClawViewController ()
@property (nonatomic, strong) MMGVideoPrizeClawView *prizeClawView;
@property (nonatomic, strong) MMGVideoPrizeClawViewModel *vpcViewModel;
@end

@implementation VideoPrizeClawViewController {
    PrizeClawVideoHandler *handler;
}

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.fd_prefersNavigationBarHidden = YES;
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
//    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    //app返回后台挂起
    MMGWeakSelf(weakSelf);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *notification) {
        
        [weakSelf closeVideoStream];
        [weakSelf.vpcViewModel closeSocket];
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *notification) {
        
        [weakSelf starVideoGame];
        [weakSelf.vpcViewModel starSocket];
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillTerminateNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *notification) {
        
        [weakSelf closeVideoStream];
        [weakSelf.vpcViewModel closeSocket];
    }];
    
    [self setUpUI];
    [self starVideoGame];
    [self.vpcViewModel starSocket];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.vpcViewModel closeSocket];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    if (self) {
        [self closeVideoStream];
        [self.vpcViewModel closeSocket];
    }
}

- (void)closeVideoStream {
    if (handler) {
        delete handler;
        handler = NULL;
        
    }
}


#pragma mark - private method
- (void)close {

    [self dismissViewControllerAnimated:YES completion:nil];
}


//TODO: - VIDEO FRAME
- (void)starVideoGame {
    
    const char *host = [kVIDEO_SERVICE_HOST UTF8String];
    const char *videoID = [kVideoID UTF8String];
    int channel = 0;
    float width = [UIScreen mainScreen].bounds.size.width;
    float height = [UIScreen mainScreen].bounds.size.height;
    
    handler = PrizeClawVideoHandler::getInstance();
    handler->starPrizeClawVideo(host, videoID, channel, width, height);
    handler->registerFrameAvailableCallBackFunction((__bridge void *)self, pcvFrameAvailableCallback);
    handler->registerFrameErrorCallBackFunction((__bridge void *)self, pcvFrameErrorCallback);
    
    [RACObserve(self,self.vpcViewModel.cameraChannel) subscribeNext:^(NSNumber *  _Nullable channel) {
        handler->setCameraChannel([channel intValue]);
    }];

}

-(void)frameError:(const char*) errorMsg {
    printf("frame error ..");
}

- (void)renderFrame:(uint8_t *)frame {
    [self.prizeClawView renderGL:frame];
}


//TODO: - SET UP UI
- (void)setUpUI {
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage mmg_imageWithColor:[UIColor mmg_colorWithHex:kMMGColorHex_MainColor]] forBarMetrics:(UIBarMetricsDefault)];
    UIImage *titleImage = [UIImage mmg_imageNamed:@"prize_claw_nav_title_icon.png"];
    UIImageView *titleView = [[UIImageView alloc] initWithImage:titleImage];
    titleView.frame = CGRectMake(0, 0, titleImage.size.width*0.8, titleImage.size.height*0.8);
    self.navigationItem.titleView = titleView;
    
    [self.prizeClawView bindDataWithViewModel:self.vpcViewModel];
    
    
//    MMGWeakSelf(weakSelf);
   
}
#pragma lazy init

- (MMGVideoPrizeClawViewModel *)vpcViewModel {
    if (!_vpcViewModel) {
        _vpcViewModel = [[MMGVideoPrizeClawViewModel alloc] init];
    }
    
    return _vpcViewModel;
}
- (MMGVideoPrizeClawView *)prizeClawView {
    if (!_prizeClawView) {
        _prizeClawView = [[MMGVideoPrizeClawView alloc] initWithFrame:self.view.bounds];
        
        [self.view addSubview:_prizeClawView];
    }
    return _prizeClawView;
}


@end
